/**
 * 城市区域管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var dialog = require("dialogplus");
    var util = require("util");
    var ui = require("ui");
    var ddl = require("dropdownlist");
    var tmpl = require("tmpl");
    require("permission");
    require("jqtree");
    require('authorize');
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/city-regional/"; //api前缀

    var CityMng = {
        token:null,
        expandLevel:false, //树的展开级别，false为不展开，0为展开1级
        cityMode: 0, //城市列表类型，0为标准，1为自定义(默认)
        dataTypeMap: {
            "group": {
                name:"城市分组",
                addUrl:"add-group",
                updateUrl:"update-group",
                delUrl:"delete-group"
            },
            "city": {
                name:"城市",
                addUrl:"add-city",
                updateUrl:"update-city",
                delUrl:"delete-city"
            },
            "district":{
                name:"城市区域",
                addUrl:"add-district",
                updateUrl:"update-district",
                delUrl:"delete-district"
            },
            "project": {
                name:"项目",
                addUrl:"",
                updateUrl:"",
                delUrl:""
            }
        },
        init: function(expandLevel) {
            this.expandLevel = expandLevel;
            this.token = util.getToken();
            this.bindEvent();
            this.initTreeTable();
            this.getCityList();
        },
        bindEvent: function() {
            var _this = this;
            $("#radio1,#radio2").on("click", function(e) {
                e.preventDefault();
                var cityMode = $(e.currentTarget).val();
                if (_this.cityMode != cityMode) {
                    _this.showChangeTip(cityMode);
                }
            });
            $("#btnAddGroup").on("click", function(e) {
                e.preventDefault();
                if (_this.cityMode == 0) {
                    _this.showPopGroup("", "");
                } else {
                    _this.showPopCity("", "");
                }
            });
        },
        initTreeTable:function(){
            var $tree = $("#tree_table");
            var _this = this;
            $tree.tree({
                saveState: "city_tree", //保存状态，使用本地存储
                data: [],
                dragAndDrop: true,
                useContextMenu:false,
                autoOpen:this.expandLevel, //展开级别
                //创建节点时
                onCreateLi: function(node, $li) {
                    var btn_str = _this.appendBtn(node);
                    $li.find(".jqtree-element").append(btn_str);
                },
                //是否可以移动
                onCanMove: function(node) {
                    if(_this.cityMode == 0 && node.data_type && node.data_type != "project"){
                        return true;
                    }
                    return false;
                },
                //是否可以移动到
                onCanMoveTo: function(moved_node, target_node,position){
                    //只能在同级节点中移动
                    //console.log(moved_node.name,target_node.name,position);
                    if(moved_node.data_type == target_node.data_type && moved_node.pid == target_node.pid 
                            && (position == "before" || position == "after")){
                        $("#tree_table .jqtree-dragging > i").removeClass("icon-op-stop");
                        return true;
                    }else{
                        $("#tree_table .jqtree-dragging > i").addClass("icon-op-stop");
                        return false;
                    }
                },
                //移动句柄
                onIsMoveHandle: function($ele) {
                    if(_this.cityMode == 0 && $ele.hasClass('jqtree-title')){
                        $ele.css("cursor","move");
                        return true;
                    }
                    return false;
                }
            });
            //绑定操作事件
            $tree.bind('tree.click',function(e){
                var node = e.node;
                if(e.click_event){
                    var className = e.click_event.target.className;
                    switch(className){
                        case "icon-op-add": //新增
                            _this.add(node);
                            break;
                        case "icon-op-edit":
                            _this.edit(node);
                            break;
                        case "icon-op-del":
                            _this.del(node);
                            break;
                        case "icon-op-link":
                            _this.getProjBindList(node);
                            break;
                        case "icon-op-unlink":
                            _this.unBindProj(node);
                            break;
                        case "icon-op-down":
                            _this.moveNode(node,node.getNextSibling(),"after");
                            break;
                        case "icon-op-up":
                            _this.moveNode(node,node.getPreviousSibling(),"before");
                            break;
                    }
                }
            });
            //移动节点前触发
           $tree.bind('tree.move',function(e) {
                    e.preventDefault(); //阻止移动
                    if(e.move_info){
                        //console.log(e.move_info.moved_node,e.move_info.target_node,e.move_info.position);
                        _this.moveNode(e.move_info.moved_node,e.move_info.target_node,e.move_info.position);
                    }
                }
            );
            $tree.bind('tree.dblclick',function(event){
                var node = event.node;
                if(node.children && node.children.length > 0){
                    if(node.is_open){
                        $("#tree_table").tree('closeNode', node,false);
                    }else{
                        $("#tree_table").tree('openNode', node,false);
                    }
                    util.clearSelection();
                }
            });
            $tree.on("mouseenter",".jqtree-element",function(){
                $(this).find(".jqtree-btn").show();
            });
            $tree.on("mouseleave",".jqtree-element",function(){
                $(this).find(".jqtree-btn").hide();
            });
        },
        /**
         * 移动节点
         * @param {node} node 原节点
         * @param {node} target_node 目的节点
         * @param {string} position 位置(before|after)
         * @returns {undefined}
         */
        moveNode:function(node,target_node,position){
            if(!target_node){
                this.showTip("节点未找到");
                return;
            }
            //移动节点
            $("#tree_table").tree('moveNode', node, target_node,position);
            //保存数据
            var parentNode = node.parent; //获取父节点
            var cities = JSON.stringify(parentNode.getData());//将父节点下所有数据序列化为json传到后台
            var url = api_prefix + "order-city";
            var data = {
                token:this.token,
                cities:cities
            };
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: data,
                success: function(json) {
                    if (json.retCode != 0) {
                        $("#tree_table").tree('moveNode',target_node, node,position); //还原位置
                        this.showTip("移动失败：" + json.errMsg);
                    }
                }
            });
        },
        //获取待绑定的项目列表
        getProjBindList:function(node){
            var url = api_prefix + "get-project-bind-list";
            var data = {
                token:this.token,
                district_id:node.id,
                city_mode:this.cityMode
            };
            util.myAjax({
                url: url,
                type: "GET",
                context: this,
                data: data,
                success: function(json) {
                     if (json.retCode == 0) {
                         var list = json.data || [];
                         this.showBindProj(node,list);
                    } else {
                        this.showTip("获取项目列表失败：" + json.errMsg);
                    }
                }
            });
        },
        checkSelAll:function(){
            var $cbs = $("#pop_proj_tbl tr.js-row input:checkbox");
            $("#pop_cb_all").prop("checked",$cbs.length == $cbs.filter(":checked").length);
            $cbs = null;
        },
        //绑定项目
        showBindProj: function(node,proj_list) {
            var _this = this;
            var str = tmpl("sel_proj_tmpl",{district_name:node.name,list:proj_list});
            var d = dialog({
                title: '区域绑定项目',
                fixed: true,
                content: str,
                width: 650,
                height:480,
                onshow:function(){
                    $("#pop_cb_all").click(function(e){
                        $("#pop_proj_tbl tr.js-row").find("input:checkbox").prop("checked",this.checked);
                    });
                    var $cbs = $("#pop_proj_tbl tr.js-row input:checkbox");
                    $cbs.on("click",function(e){
                        e.stopPropagation();
                        _this.checkSelAll();
                    });
                    $("#pop_proj_tbl tr.js-row").on("click",function(e){
                        var tagName = e.target.tagName.toLowerCase();
                        if(tagName == "tr" || tagName == "td"){
                            var $cb = $(this).find("input:checkbox");
                            $cb.prop("checked",!$cb.prop("checked"));
                            _this.checkSelAll();
                        }
                    });
                },
                ok: function() {
                    var url = api_prefix + "bind-project";
                    var $cb_list = $("#pop_proj_tbl tr.js-row").find("input:checkbox:checked");
                    var arr = [];
                    $cb_list.each(function(i,cb){
                        arr.push(cb.id);
                    });
                    if(arr.length == 0){
                        ui.showErrTip("请选择要绑定的项目");
                        return false;
                    }
                    var data = {
                        token:_this.token,
                        district_id:node.id,
                        proj_ids:JSON.stringify(arr)
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                _this.getCityList();
                            } else {
                                _this.showTip("删除失败：" + json.errMsg);
                            }
                        }
                    });
                    return true;
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        //取消绑定项目
        unBindProj: function(node) {
            if(!node){
                return;
            }
            var _this = this;
            util.confirm("您确定要取消绑定项目吗？",{
                ok:function(){
                    var url = api_prefix + "un-bind-project";
                    var data = {
                        token:_this.token,
                        proj_id:node.id,
                        city_id:node.pid,
                        city_mode:_this.cityMode
                    };
                    util.myAjax({
                        url: url,
                        type: "POST",
                        data: data,
                        success: function(json) {
                             if (json.retCode == 0) {
                                _this.getCityList();
                            } else {
                                _this.showTip("取消绑定失败：" + json.errMsg);
                            }
                        }
                    });
                }
            });
        },
        del: function(node) {
            if(node.children && node.children.length > 0){
                util.alert("存在子节点，不允许删除",{okValue:"关闭"});
                return;
            }
            var data_type = node["data_type"];
            var obj = this.dataTypeMap[data_type];
            var _this = this;
            util.confirm("您确定要删除" + obj.name + "吗？",{
                ok:function(){
                    var url = api_prefix + obj["delUrl"];
                    var data = {
                        token:_this.token
                    };
                    if(data_type == "group"){
                        data.group_id = node.id;
                    }else if(data_type == "city"){
                        data.city_id = node.id;
                    }else if(data_type == "district"){
                        data.district_id = node.id;
                    }
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: _this,
                        data: data,
                        success: function(json) {
                            if (json.retCode == 0) {
                                this.getCityList();
                            } else {
                                this.showTip("删除失败：" + json.errMsg);
                            }
                        }
                    });
                    return true;
                }
            });
        },
        add: function(node) {
            switch (node["data_type"]) {
                case "group": //分组下新增城市
                    this.addGroupCity(node["id"], node["name"]);
                    break;
                case "city": //城市下新增区域
                    if(this.cityMode == 0){
                        this.getCityDistrict(node["id"],node["name"],node["zipcode"]);
                    }else{
                        this.showPopDistrict(node["id"], node["name"], "", "");
                    }
                    break;
            }
        },
        edit: function(node) {
            switch (node["data_type"]) {
                case "group":
                    this.showPopGroup(node["id"], node["name"]);
                    break;
                case "city":
                    this.showPopCity(node["id"], node["name"]);
                    break;
                case "district":
                    var pNode = node.parent; //获取父结点
                    this.showPopDistrict(pNode["id"], pNode["name"], node["id"], node["name"]);
                    break;
            }
        },
        showTip: function(msg) {
            util.alert(msg);
        },
        //新增城市分组
        showPopGroup: function(group_id, group_name) {
            var title = group_id ? "编辑城市分组" : "新增城市分组";
            group_name = group_name || "";
            var _this = this;
            var str = '<div style="margin-left:30px;" class="clearfix lh30"><label class="fl">城市分组名称：</label>'
                    + '<div class="fl"><input class="input-text" style="width:220px;" text="text" maxlength="20" value="' + group_name + '" />'
                    + '<div class="c-red f13 js-err"></div></div></div>';
            var d = dialog({
                title: title,
                content: str,
                fixed: true,
                width: 400,
                height: 60,
                okValue: "保存",
                ok: function() {
                    var $content = this._$('content');
                    var $input = $content.find("input");
                    var $err = $content.find(".js-err");
                    var group_name = $.trim($input.val());
                    if (group_name) {
                        $err.html("");
                        _this.saveGroup(group_id, group_name);
                        return true;
                    } else {
                        $err.html("请输入分组名称");
                        $input.focus();
                        return false;
                    }
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        //保存分组
        saveGroup: function(group_id, group_name) {
            var post_data = {
                token:this.token,
                group_name: group_name
            };
            var url;
            if (group_id) {
                url = api_prefix + "update-group";
                post_data.group_id = group_id;
            }else{
                url = api_prefix + "add-group";
            }
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: post_data,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.getCityList();
                    } else {
                        this.showTip("保存失败：" + json.errMsg);
                    }
                }
            });
        },
        //新增,编辑城市
        showPopCity: function(city_id, city_name) {
            var _this = this;
            var title = city_id ? "编辑城市" : "新增城市";
            var str = '<div style="margin-left:30px;margin-top:10px;" class="clearfix lh30"><label class="fl">城市名称：</label>'
                    + '<div class="fl"><input class="input-text" style="width:220px;" text="text" maxlength="20" value="' + city_name + '" />'
                    + '<div class="c-red f13 js-err"></div></div></div>';

            var d = dialog({
                title: title,
                content: str,
                fixed: true,
                width: 400,
                height: 60,
                okValue: "保存",
                ok: function() {
                    var $content = this._$('content');
                    var $input = $content.find("input");
                    var $err = $content.find(".js-err");
                    var city_name = $.trim($input.val());
                    if (city_name) {
                        $err.html("");
                        _this.saveCity(city_id, city_name);
                        return true;
                    } else {
                        $err.html("请输入城市名称");
                        $input.focus();
                        return false;
                    }
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        //分组下新增城市
        addGroupCity: function(group_id, group_name) {
            if (!this.provinces) {
                var url = api_prefix + "get-provinces";
                util.myAjax({
                    url: url,
                    type: "get",
                    context: this,
                    data:{
                        token:this.token
                    },
                    success: function(json) {
                        this.provinces = json.data || [];
                        this.provinces.unshift(["请选择", ""]);
                        this.showAddGroupCity(group_id, group_name);
                    }
                });
            } else {
                this.showAddGroupCity(group_id, group_name);
            }
        },
        showAddGroupCity: function(group_id, group_name) {
            var _this = this;
            var title = "新增城市";
            var str = '<div style="margin-left:65px;margin-top:10px;">'
                    + '<div style="line-height:30px;margin-bottom:18px;">城市分组名称：<span class="c-ff7713">' + group_name + '</span></div>'
                    + '<div class="clearfix lh30"><div id="province_container" class="fl" style="margin-right:10px;"></div>'
                    + '<div id="city_container" class="fl"></div></div>'
                    + '<div class="c-red lh30 js-err f13"></div>'
                    + '</div>';
            var d = dialog({
                title: title,
                fixed: true,
                content: str,
                width: 500,
                height: 150,
                okValue: "保存",
                onshow: function() {
                    var ddl_province = ddl.create({
                        container: $('#province_container'),
                        attrs: {
                            id: 'ddl_province'
                        },
                        options: _this.provinces
                    }).change(function(e) {
                        var province_code = $("#ddl_province").val();
                        _this.getProvinceCitys(province_code);
                    });
                    ddl.create({
                        container: $('#city_container'),
                        attrs: {
                            id: 'ddl_city'
                        },
                        options: [
                            ["请选择", ""]
                        ]
                    });
                },
                ok: function() {
                    var $content = this._$('content');
                    var $err = $content.find(".js-err");
                    var ddl_province = $("#ddl_province").get(0);
                    var province_code = ddl_province.options[ddl_province.selectedIndex].value;
                    var ddl_city = $("#ddl_city").get(0);
                    var city_name = ddl_city.options[ddl_city.selectedIndex].text;
                    var city_code = ddl_city.options[ddl_city.selectedIndex].value;
                    if (!province_code || province_code == "请选择") {
                        $err.html("请选择省份");
                        return false;
                    }
                    if (!city_code || city_code == "请选择") {
                        $err.html("请选择城市");
                        return false;
                    }
                    $err.html("");
                    _this.saveGroupCity(group_id, city_name, city_code);
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        //在分组上新增城市
        saveGroupCity: function(group_id, city_name,city_code) {
            var url = api_prefix + "add-city";
            util.myAjax({
                url: url,
                type: "POST",
                context:this,
                data: {
                    token:this.token,
                    city_name:city_name,
                    parent_id: group_id,
                    zipcode:city_code
                },
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.getCityList();
                    } else {
                        this.showTip("保存失败：" + json.errMsg);
                    }
                }
            });
        },
        //加载省份下的城市
        getProvinceCitys: function(province_code) {
            province_code = province_code == "请选择" ? "" : province_code;
            var url = api_prefix + "get-cities";
            util.myAjax({
                url: url,
                type: "get",
                data: {
                    token:this.token,
                    province_code: province_code
                },
                context: this,
                success: function(json) {
                    var citys = json.data || [];
                    citys.unshift(["请选择", ""]);
                    ddl.create({
                        container: $('#city_container'),
                        attrs: {
                            id: 'ddl_city'
                        },
                        options: citys
                    });
                }
            });
        },
        //新增，编辑城市
        saveCity: function(city_id, city_name) {
            var post_data = {
                token:this.token,
                city_name: city_name
            };
            var url;
            if (city_id) {
                url = "update-city";
                post_data["city_id"] = city_id;
            }else{
                url = "add-city";
            }
            util.myAjax({
                url: api_prefix + url,
                type: "POST",
                cache: false,
                context: this,
                data: post_data,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.getCityList();
                    } else {
                        this.showTip("保存失败：" + json.errMsg);
                    }
                }
            });
        },
        //自定义模式，新增编辑城市区域
        showPopDistrict: function(p_id, p_name, district_id, district_name) {
            district_name = district_name || "";
            var title = district_id ? "编辑城市区域" : "新增城市区域";
            var str = '<div style="margin-left:38px;">'
                    + '<div class="clearfix lh30" style="margin-bottom:5px;"><label class="fl">父级城市：</label>'
                    + '<div class="fl c-ff7713">' + p_name + '</div></div>'
                    + '<div class="clearfix lh30"><label class="fl">区域名称：</label>'
                    + '<div class="fl"><input class="input-text" style="width:220px;" text="text" maxlength="20" value="' + district_name + '" />'
                    + '<div class="c-red js-err f13"></div></div></div>'
                    + '</div>';

            var _this = this;
            var d = dialog({
                title: title,
                fixed: true,
                content: str,
                width: 400,
                height: 70,
                okValue: "保存",
                ok: function() {
                    var $content = this._$('content');
                    var $input = $content.find("input");
                    var $err = $content.find(".js-err");
                    var district_name = $.trim($input.val());
                    if (district_name) {
                        $err.html("");
                        _this.saveDistrict(p_id, p_name, district_id, district_name);
                        return true;
                    } else {
                        $err.html("请输入区域名称");
                        $input.focus();
                        return false;
                    }
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        getCityDistrict:function(city_id,city_name,zipcode){
            var url = api_prefix + "get-districts";
            util.myAjax({
                url: url,
                type: "get",
                context: this,
                data:{
                    token:this.token,
                    city_code:zipcode
                },
                success: function(json) {
                    var list = json.data || [];
                    this.showAddCityDistrict(city_id,city_name,list);
                }
            });
        },
        //标准模式，新增编辑城市区域
        showAddCityDistrict:function(city_id, city_name,district_list){
            var title = "新增市区";
            var cbList = "";
            $.each(district_list,function(i,item){
                cbList += '<div class="checkbox fl" style="margin-right:8px;">';
                if(item.selected == 1){ //已选择的不能再选
                    cbList += '<input type="checkbox" name="cb_districts" class="cb-disabled" id="cb_' + item.code + '" disabled checked value="' + item.code + '" />'
                }else{
                    cbList += '<input type="checkbox" name="cb_districts" id="cb_' + item.code + '"  value="' + item.code + '" />'
                }
                cbList += '<label for="cb_' + item.code + '">' + item.name + '</label>'  
                cbList += '</div>';
            });
            var str = '<div style="margin-left:38px;">'
                    + '<div class="clearfix lh30" style="margin-bottom:5px;"><label class="fl">父级城市名称：</label>'
                    + '<div class="fl c-ff7713">' + city_name + '</div></div>'
                    + '<div class="clearfix lh30"><label class="fl">选择新增市区：</label>'
                    + '<div class="fl" style="width:400px;max-height:210px;overflow: auto;">'
                    + cbList
                    + '<div class="c-red f13 js-err"></div></div></div>'
                    + '</div>';

            var _this = this;
            var d = dialog({
                title: title,
                fixed: true,
                content: str,
                width: 550,
                okValue: "保存",
                ok: function() {
                    var $content = this._$('content');
                    var $cb_list = $content.find("input[name='cb_districts']").filter(":checked");
                    var arr = [];
                    $cb_list.each(function(i,item){
                        if(!item.disabled){
                            arr.push({
                                parent_id:city_id,
                                district_name:$(item).next("label").text()
                            });
                        }
                    });
                    if (arr.length > 0) {
                        var post_data = {
                            token:_this.token,
                            districts:JSON.stringify(arr)
                        };
                        util.myAjax({
                            url: api_prefix + "add-districts",
                            type: "POST",
                            cache: false,
                            data: post_data,
                            success: function(json) {
                                if (json.retCode == 0) {
                                    _this.getCityList();
                                } else {
                                    _this.showTip("保存失败：" + json.errMsg);
                                }
                            }
                        });
                        return true;
                    }
                },
                cancel: function() {
                }
            });
            d.showModal();
        },
        saveDistrict: function(parent_id, parent_name, district_id, district_name) {
            var post_data;
            var url;
            if (district_id) {
                post_data = {
                    token:this.token,
                    district_id:district_id,
                    district_name:district_name
                };
                url = "update-district";
            }else{
                var arr = [{
                    district_name:district_name,
                    parent_id:parent_id
                }];
                post_data = {
                    token:this.token,
                    districts:JSON.stringify(arr)
                };
                url =  "add-districts";
            }
            util.myAjax({
                url: api_prefix + url,
                type: "POST",
                cache: false,
                context: this,
                data: post_data,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.getCityList();
                    } else {
                        this.showTip("保存失败：" + json.errMsg);
                    }
                }
            });
        },
        /**
         * 切换城市列表类型
         */
        showChangeTip: function(cityMode) {
            var infoText = '<div style="margin-left:15px;"><div style="margin-bottom:5px;">切换城市区域列表类型，会影响前端展示！</div>'
                        + '<ul style="margin-bottom:15px;margin-left:10px;"><li>1.标准设置有城市分组，根据地理位置定位城市的展示。</li>'
                        + '<li>2.自定义设置没有城市分组，无法使用地理位置识别。</li></ul>'
                        + '<div>确定要切换模式吗？</div></div>';
            var _this = this;
            var d = dialog({
                title: '提示',
                fixed: true,
                content: infoText,
                width: 400,
                ok: function() {
                    _this.saveCityMode(cityMode);
                    return true;
                },
                cancel: function() {
                    _this.setCityMode();
                }
            });
            d.showModal();
        },
        setCityMode: function() {
            if (this.cityMode == 0) {
                $("#radio1").prop("checked", true);
                $("#btnAddGroup").css("width","130px").find("span").html("新增城市分组");
                $("#drag_tip").show();
            } else {
                $("#radio2").prop("checked", true);
                $("#btnAddGroup").css("width","112px").find("span").html("新增城市");
                $("#drag_tip").hide();
            }
        },
        //保存城市列表类型
        saveCityMode: function(cityMode) {
            var url = api_prefix + "update-city-mode";
            util.myAjax({
                url: url,
                type: "POST",
                cache: false,
                context: this,
                data: {
                    token:this.token,
                    city_mode: cityMode
                },
                success: function(json) {
                    if (json.retCode == 0) {
                        this.cityMode = cityMode;
                        this.setCityMode();
                        this.getCityList();
                    } else {
                        this.showTip("保存城市列表类型失败：" + json.errMsg);
                    }
                }
            });
        },
        /**
         * 加载城市区域列表数据
         * @returns {undefined}
         */
        getCityList: function() {
            var url = api_prefix + "get-city-list";
            util.myAjax({
                url: url,
                type: "GET",
                cache: false,
                data:{
                    token:this.token
                },
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        this.cityMode = json.city_mode;
                        this.cityList = json.data || [];
                        this.setCityMode();
                        $('#tree_table').tree('loadData', this.cityList);
                    } else {
                        this.showTip("加载城市列表失败:" + json.errMsg);
                    }
                }
            });
        },
        /**
         * 获取每一行的操作按钮
         */
        appendBtn: function(node) {
            var data_type = node["data_type"] || "";
            var str = '<div class="jqtree-btn" style="display:none;">';
            var actionCls = "permission p-500309-09-inline-block"; //权限点样式
            switch (data_type) {
                case "group":
                    str += this.getBtnHtml("新增城市","icon-op-add",actionCls);
                    str += this.getBtnHtml("编辑分组","icon-op-edit",actionCls);
                    str += this.getBtnHtml("删除分组","icon-op-del",actionCls);
                    break;
                case "city":
                    str += this.getBtnHtml("新增区域","icon-op-add",actionCls);
                    if (this.cityMode == 1) {
                        str += this.getBtnHtml("编辑城市","icon-op-edit",actionCls);
                    }
                    str += this.getBtnHtml("删除城市","icon-op-del",actionCls);
                    break;
                case "district":
                    str += this.getBtnHtml("绑定项目","icon-op-link",actionCls);
                    if (this.cityMode == 1) {
                        str += this.getBtnHtml("编辑区域","icon-op-edit",actionCls);
                    }
                    str += this.getBtnHtml("删除区域","icon-op-del",actionCls);
                    break;
                case "project":
                    str += this.getBtnHtml("取消绑定","icon-op-unlink",actionCls);
                    break;
            }
            //上移下移按钮
            if (data_type != "project" && this.cityMode == 0) {
                var isFirstNode = node.getPreviousSibling() == null; //同级第一个节点
                var isLastNode = node.getNextSibling() == null; //同级最后一个节点
            
                if (!isLastNode) { //下移权限
                    str += this.getBtnHtml("下移","icon-op-down",actionCls);
                }
                if (!isFirstNode) { //上移权限
                    str += this.getBtnHtml("上移","icon-op-up",actionCls);
                }
            }
            return str + "</div>";
        },
        getBtnHtml:function(title,iconCls,actionCls){
            return '<a href="javascript:void(0)" title="' + title + '" class="' + actionCls + '"><i class="' + iconCls + '">&nbsp;</i></a>';
        }
    };
    module.exports = CityMng;
});